package com.cy.ppj.web.admin.order;

import com.cy.ppj.model.enums.ManagerType;
import com.cy.ppj.model.enums.MessageType;
import com.cy.ppj.service.message.MessageService;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.cy.ppj.comm.constant.Constants;
import com.cy.ppj.comm.utils.CommonUtils;
import com.cy.ppj.comm.utils.ExportExcelUtils;
import com.cy.ppj.model.PageBean;
import com.cy.ppj.model.Result;
import com.cy.ppj.model.ao.order.OrderAdminAddAO;
import com.cy.ppj.model.ao.order.OrderAdminEditAO;
import com.cy.ppj.model.ao.order.OrderAuditAO;
import com.cy.ppj.model.ao.order.OrderEditAO;
import com.cy.ppj.model.ao.order.OrderExtSetAO;
import com.cy.ppj.model.ao.order.OrderWithholdSetAO;
import com.cy.ppj.model.domian.order.Order;
import com.cy.ppj.model.dto.manager.ManagerLoginDTO;
import com.cy.ppj.model.dto.order.OrderImportDTO;
import com.cy.ppj.model.dto.order.ToDayLoanSuccessOrderCountDTO;
import com.cy.ppj.model.query.AuditManagerQuery;
import com.cy.ppj.model.query.OrderAdminQuery;
import com.cy.ppj.model.query.order.DecorationPassOrderListAdminQuery;
import com.cy.ppj.model.query.order.OrderCountQuery;
import com.cy.ppj.model.vo.AuditManagerVO;
import com.cy.ppj.model.vo.OrderAdminVO;
import com.cy.ppj.model.vo.OrderDetailAdminVO;
import com.cy.ppj.model.vo.admin.order.DecorationPassOrderListAdminVO;
import com.cy.ppj.model.vo.order.FurnitureGoodsOrderDetailAdminVO;
import com.cy.ppj.service.manager.ManagerService;
import com.cy.ppj.service.order.OrderService;
import com.cy.ppj.service.product.ProductService;
import com.cy.ppj.web.BaseController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;

/**
 * 后台-订单管理
 * @author: tanyilin
 * @create: 2018年7月21日 下午5:36:54
 */
@Slf4j
@RestController
@RequestMapping("/admin/order")
@Api(tags = "后台-订单管理")
public class AdminOrderController extends BaseController{

	@Autowired
	private OrderService orderService;
	@Autowired
	private ProductService productService;
	@Autowired
	private ManagerService managerService;
	@Autowired
	private MessageService messageService;
	
	@ApiOperation("全部-订单列表")
	@GetMapping("/list")
	public PageBean<OrderAdminVO> list(OrderAdminQuery query) {
		// 当前登录的管理员账户
		ManagerLoginDTO manager = this.getManager();
		PageBean<OrderAdminVO> pageBean = new PageBean<>(null, 0);
		
		if(ManagerType.GENERAL_MANAGER.equals(manager.getType())) {
			// 综合管理员
			query.setType(1);
			pageBean = orderService.selectAllOrderAdminList(query);
			
		}else if(ManagerType.CITY_LEADER.equals(manager.getType())) {
			// 城市负责人
			query.setType(2);
			query.setCityId(manager.getCityId());
			pageBean = orderService.selectAllOrderAdminList(query);
			
		}else if(ManagerType.COMPANY_LEADER.equals(manager.getType())) {
			// 渠道公司负责人
			query.setType(3);
			query.setCompanyId(manager.getCompanyId());
			pageBean = orderService.selectAllOrderAdminList(query);
		}
		
		return pageBean;
	}
	
	@ApiOperation("待接单（未分配）-订单列表")
	@GetMapping("/unassigned/list")
	public PageBean<OrderAdminVO> unassignedList(OrderAdminQuery query) {
		// 当前登录的管理员账户
		ManagerLoginDTO manager = this.getManager();
		PageBean<OrderAdminVO> pageBean = new PageBean<>(null, 0);
		
		if(ManagerType.GENERAL_MANAGER.equals(manager.getType())) {
			// 综合管理员
			query.setType(1);
			pageBean = orderService.selectUnassignedOrderAdminList(query);
			
		}else if(ManagerType.CITY_LEADER.equals(manager.getType())) {
			// 城市负责人
			query.setType(2);
			query.setCityId(manager.getCityId());
			pageBean = orderService.selectUnassignedOrderAdminList(query);
			
		}else if(ManagerType.COMPANY_LEADER.equals(manager.getType())) {
			// 渠道公司负责人
			query.setType(3);
			query.setCompanyId(manager.getCompanyId());
			pageBean = orderService.selectUnassignedOrderAdminList(query);
		}
		
		return pageBean;
	}
	
	@ApiOperation("处理中-订单列表")
	@GetMapping("/processing/list")
	public PageBean<OrderAdminVO> processingList(OrderAdminQuery query) {
		// 当前登录的管理员账户
		ManagerLoginDTO manager = this.getManager();
		PageBean<OrderAdminVO> pageBean = new PageBean<>(null, 0);
		if(Constants.AUDIT_ROLE_ID.equals(manager.getRoleId())) {
			// 如果当前管理员是审核人员角色，那就只能查看他所接的单
			query.setManagerId(manager.getManagerId());
		}
		if(ManagerType.GENERAL_MANAGER.equals(manager.getType())) {
			// 综合管理员
			query.setType(1);
			pageBean = orderService.selectProcessingOrderAdminList(query);
			
		}else if(ManagerType.CITY_LEADER.equals(manager.getType())) {
			// 城市负责人
			query.setType(2);
			query.setCityId(manager.getCityId());
			pageBean = orderService.selectProcessingOrderAdminList(query);
			
		}else if(ManagerType.COMPANY_LEADER.equals(manager.getType())) {
			// 渠道公司负责人
			query.setType(3);
			query.setCompanyId(manager.getCompanyId());
			pageBean = orderService.selectProcessingOrderAdminList(query);
		}
		
		return pageBean;
	}
	
	@ApiOperation("已批款-订单列表")
	@GetMapping("/pass/list")
	public PageBean<OrderAdminVO> passList(OrderAdminQuery query) {
		// 当前登录的管理员账户
		ManagerLoginDTO manager = this.getManager();
		PageBean<OrderAdminVO> pageBean = new PageBean<>(null, 0);
		if(Constants.AUDIT_ROLE_ID.equals(manager.getRoleId())) {
			// 如果当前管理员是审核人员角色，那就只能查看他所接的单
			query.setManagerId(manager.getManagerId());
		}
		if(ManagerType.GENERAL_MANAGER.equals(manager.getType())) {
			// 综合管理员
			query.setType(1);
			pageBean = orderService.selectPassOrderAdminList(query);
			
		}else if(ManagerType.CITY_LEADER.equals(manager.getType())) {
			// 城市负责人
			query.setType(2);
			query.setCityId(manager.getCityId());
			pageBean = orderService.selectPassOrderAdminList(query);
			
		}else if(ManagerType.COMPANY_LEADER.equals(manager.getType())) {
			// 渠道公司负责人
			query.setType(3);
			query.setCompanyId(manager.getCompanyId());
			pageBean = orderService.selectPassOrderAdminList(query);
		}
		
		return pageBean;
	}
	
	@ApiOperation("已拒绝-订单列表")
	@GetMapping("/reject/list")
	public PageBean<OrderAdminVO> rejectList(OrderAdminQuery query) {
		// 当前登录的管理员账户
		ManagerLoginDTO manager = this.getManager();
		PageBean<OrderAdminVO> pageBean = new PageBean<>(null, 0);
		if(Constants.AUDIT_ROLE_ID.equals(manager.getRoleId())) {
			// 如果当前管理员是审核人员角色，那就只能查看他所接的单
			query.setManagerId(manager.getManagerId());
		}
		if(ManagerType.GENERAL_MANAGER.equals(manager.getType())) {
			// 综合管理员
			query.setType(1);
			pageBean = orderService.selectRejectOrderAdminList(query);
			
		}else if(ManagerType.CITY_LEADER.equals(manager.getType())) {
			// 城市负责人
			query.setType(2);
			query.setCityId(manager.getCityId());
			pageBean = orderService.selectRejectOrderAdminList(query);
			
		}else if(ManagerType.COMPANY_LEADER.equals(manager.getType())) {
			// 渠道公司负责人
			query.setType(3);
			query.setCompanyId(manager.getCompanyId());
			pageBean = orderService.selectRejectOrderAdminList(query);
		}
		
		return pageBean;
	}
	
	@ApiOperation("已分配订单列表，该api暂时不用了")
	@GetMapping("/assigned/list")
	public PageBean<OrderAdminVO> assignedList(OrderAdminQuery orderAdminQuery) {
		orderAdminQuery.setType(3);
		orderAdminQuery.setManagerId(this.getManager().getManagerId());
		return orderService.queryOrderAdminList(orderAdminQuery);
	}
	
	@ApiOperation("放款通过")
	@PostMapping("/loan/success")
	public Result loanSuccess(@Validated OrderEditAO orderEditAO, BindingResult bindingResult) {
		state(Constants.AUDIT_ROLE_ID.equals(this.getManager().getRoleId()), "非审核员不可审核订单");
		this.checkError(bindingResult);
		Order order = new Order();
		BeanUtils.copyProperties(orderEditAO, order);
		orderService.orderLoanSuccess(order, this.getManager().getManagerId());
		messageService.sendMessage(String.valueOf(orderEditAO.getId()), MessageType.ORDER);
		return ok();
	}
	
	@ApiOperation("审核订单")
	@PostMapping("/audit")
	public Result audit(@Validated OrderAuditAO orderAuditAO, BindingResult bindingResult) {
		state(Constants.AUDIT_ROLE_ID.equals(this.getManager().getRoleId()), "非审核员不可审核订单");
		if(!orderAuditAO.getIsPass()) {
			// 如果审核结果是拒绝，判断拒绝类型是否为空
			boolean flag = CommonUtils.isEmpty(orderAuditAO.getRejectType());
			state(!flag, "请选择拒绝类型");
		}
		this.checkError(bindingResult);
		orderService.auditOrder(orderAuditAO, this.getManager().getManagerId());
		messageService.sendMessage(String.valueOf(orderAuditAO.getId()), MessageType.ORDER);
		return ok();
	}
	
	@ApiOperation("分配审核员")
	@PostMapping("/assign/manager")
	public Result assignUser(@ApiParam(value = "订单id", example = "0", required = true) @RequestParam Long orderId,
			@ApiParam(value = "管理员用户id", example = "0", required = true) @RequestParam Long managerId) {
		
		orderService.assignUser(orderId, managerId);
		return ok();
	}
	
	@ApiOperation("接单")
	@PostMapping("/receive")
	public Result receive(@ApiParam(value = "订单id", example = "0", required = true) @RequestParam Long orderId) {
		
		orderService.assignUser(orderId, this.getManager().getManagerId());
		
		return ok();
	}
	
	@ApiOperation("获取产品对应的期限列表")
	@GetMapping("/get/periods")
	public Result queryPeriodsByOrderId(@ApiParam(value = "订单id", example = "0", required = true) @RequestParam Long orderId) {
		return productService.queryPeriodsByOrderId(orderId);
	}
	
	@ApiOperation("获取系统的审核员管理账户列表")
	@GetMapping("/get/audit/managers")
	public PageBean<AuditManagerVO> getAuditManagers(AuditManagerQuery auditManagerQuery) {
		auditManagerQuery.setRoleId(Constants.AUDIT_ROLE_ID);
		return managerService.selectAuditManagerList(auditManagerQuery);
	}
	
	@ApiOperation("设置代扣参数信息")
	@PostMapping("/set/withhold")
	public Result setOrderWithhold(@Validated OrderWithholdSetAO orderWithholdSetAO, BindingResult bindingResult) {
		this.checkError(bindingResult);
		orderService.setOrderWithhold(orderWithholdSetAO);
		return ok();
	}
	
	@ApiOperation("设置外部单号")
	@PostMapping("/set/ext")
	public Result setOrderExt(@Validated OrderExtSetAO orderExtSetAO, BindingResult bindingResult) {
		this.checkError(bindingResult);
		orderService.setOrderExt(orderExtSetAO);
		return ok();
	}
	
	@ApiOperation("获取今日交单数")
	@GetMapping("/get/today/apply/count")
	public Result getToDayApplyOrderCount() {
		// 当前登录的管理员账户
		ManagerLoginDTO manager = this.getManager();
		int count = 0;
		OrderCountQuery query = new OrderCountQuery();
		if(ManagerType.GENERAL_MANAGER.equals(manager.getType())) {
			// 综合管理员
			count = orderService.selectToDayApplyOrderCount(query);
			
		}else if(ManagerType.CITY_LEADER.equals(manager.getType())) {
			// 城市负责人
			query.setCityId(manager.getCityId());
			count = orderService.selectToDayApplyOrderCount(query);
			
		}else if(ManagerType.COMPANY_LEADER.equals(manager.getType())) {
			// 渠道公司负责人
			query.setCompanyId(manager.getCompanyId());
			count = orderService.selectToDayApplyOrderCount(query);
		}
		
		return ok("", count);
	}
	
	@ApiOperation("获取今日批款单数")
	@GetMapping("/get/today/loan/count")
	public Result<ToDayLoanSuccessOrderCountDTO> getToDayLoanSuccessOrderCount() {
		// 当前登录的管理员账户
		ManagerLoginDTO manager = this.getManager();
		ToDayLoanSuccessOrderCountDTO dto = new ToDayLoanSuccessOrderCountDTO();
		OrderCountQuery query = new OrderCountQuery();
		if(ManagerType.GENERAL_MANAGER.equals(manager.getType())) {
			// 综合管理员
			dto = orderService.selectToDayLoanSuccessOrderCount(query);
			
		}else if(ManagerType.CITY_LEADER.equals(manager.getType())) {
			// 城市负责人
			query.setCityId(manager.getCityId());
			dto = orderService.selectToDayLoanSuccessOrderCount(query);
			
		}else if(ManagerType.COMPANY_LEADER.equals(manager.getType())) {
			// 渠道公司负责人
			query.setCompanyId(manager.getCompanyId());
			dto = orderService.selectToDayLoanSuccessOrderCount(query);
		}
		
		return ok("", dto);
	}
	
	@ApiOperation("获取今日拒绝单数")
	@GetMapping("/get/today/reject/count")
	public Result getToDayRejectOrderCount() {
		// 当前登录的管理员账户
		ManagerLoginDTO manager = this.getManager();
		int count = 0;
		OrderCountQuery query = new OrderCountQuery();
		if(ManagerType.GENERAL_MANAGER.equals(manager.getType())) {
			// 综合管理员
			count = orderService.selectToDayRejectOrderCount(query);
			
		}else if(ManagerType.CITY_LEADER.equals(manager.getType())) {
			// 城市负责人
			query.setCityId(manager.getCityId());
			count = orderService.selectToDayRejectOrderCount(query);
			
		}else if(ManagerType.COMPANY_LEADER.equals(manager.getType())) {
			// 渠道公司负责人
			query.setCompanyId(manager.getCompanyId());
			count = orderService.selectToDayRejectOrderCount(query);
		}
		
		return ok("", count);
	}
	
	@ApiOperation("导出Excel")
	@GetMapping("/list/export/excel")
	public void listExportExcel(OrderAdminQuery query, HttpServletRequest req, HttpServletResponse resp) {
		query.setPage(1);
		query.setLimit(5000);
		List<OrderAdminVO> data = this.list(query).getData();
		String title = "全部订单列表";
		String[] headers = {"订单编号", "客户姓名", "身份证号码", "代扣产品", "申请金额", "申请时间", 
				"更新时间", "订单状态", "代扣", "佣金", "接单员", "经纪人", "业务员", "城市"};
		String[] fieldNames = {"id", "customerName", "idNo", "productName", "loanAmount", "createTime", 
				"updateTime", "orderStatusText", "withholdRateText", "commissionRateText", "assignUserName", "recommenderName", "salesName", "city"};
		ExportExcelUtils<OrderAdminVO> ex = new ExportExcelUtils<>();
		try(OutputStream out = resp.getOutputStream()) {
			req.setCharacterEncoding("UTF-8");
			resp.setCharacterEncoding("UTF-8");
			resp.setContentType("application/x-download");
			String fileName = CommonUtils.getCurrentTimeAndRandomNumber().concat(".xls");
			fileName = new String(fileName.getBytes("gb2312"), "ISO8859-1");
			resp.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			ex.exportExcel(title, headers, fieldNames, data, out);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@ApiOperation("导入订单")
    @PostMapping("/import/excel")
	public Result improtExcel(@ApiParam(value = "Excel表格", required = true) @RequestParam MultipartFile file){
		//解析Excel表格数据
		List<OrderImportDTO> orderImportList = orderService.getOrderImportDTO(file);
		if(CommonUtils.isEmpty(orderImportList)) {
			return fail("表格数据为空");
		}
		//添加委案
		orderService.importOrder(orderImportList);
		return ok("导入成功", orderImportList);
	}
	
	@ApiOperation("已批款（装修贷）列表")
	@GetMapping("/pass/decoration/list")
	public PageBean<DecorationPassOrderListAdminVO> selectDecorationPassOrderListAdmin(DecorationPassOrderListAdminQuery query) {
		PageBean<DecorationPassOrderListAdminVO> pageBean = orderService.selectDecorationPassOrderListAdmin(query);
		return pageBean;
	}
	
	@ApiOperation("编辑订单信息")
	@PostMapping("/edit")
	public Result edit(@Validated OrderEditAO orderEditAO, BindingResult bindingResult) {
		this.checkError(bindingResult);
		Order order = new Order();
		BeanUtils.copyProperties(orderEditAO, order);
		orderService.updateOrder(order);
		return ok();
	}
	
	@ApiOperation("后台新增订单")
	@PostMapping("/do/add")
	public Result doAdd(@RequestBody @Validated OrderAdminAddAO addAO, BindingResult bindingResult) {
		this.checkError(bindingResult);
		
		orderService.addOrder(addAO, this.getManager().getManagerId());
		
		return ok();
	}
	
	@ApiOperation("后台订单详情")
	@GetMapping("/detail")
	public Result<OrderDetailAdminVO> selectOrderDetailAdminVO(@RequestParam(value = "orderId") Long orderId) {
		OrderDetailAdminVO resultVo = orderService.selectOrderDetailAdminVO(orderId);
		return ok("", resultVo);
	}
	
	@ApiOperation("后台编辑订单")
	@PostMapping("/do/edit")
	public Result doEdit(@RequestBody @Validated OrderAdminEditAO editAO, BindingResult bindingResult) {
		this.checkError(bindingResult);
		
		orderService.updateOrder(editAO);
		
		return ok();
	}
	
	@ApiOperation("家具分期商品订单详情(暂不使用)")
	@GetMapping("/get/furniture/goods/order/detail222")
	public Result<FurnitureGoodsOrderDetailAdminVO> selectFurnitureGoodsOrderDetailAdminVO(@RequestParam(value = "orderId") Long orderId) {
		FurnitureGoodsOrderDetailAdminVO resultVo = orderService.selectFurnitureGoodsOrderDetailAdminVO(orderId);
		return ok("", resultVo);
	}
	
	
}
